package yxy.game.pm2.command.union.leader;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.module.RedisLock;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.UnionLeaderMessage;
import yxy.game.pm2.module.union.UnionBean;
import yxy.game.pm2.module.union.UnionHandle;
import yxy.game.pm2.module.union.UnionHandle.UnionPlayerEntry;

/** 联盟盟主 联盟盟主转让 */
@MessageType(proto = Command.UnionAbdicate, classtype = UnionLeaderMessage.UnionAbdicateRequest.class)
public class CMD_UnionAbdicate extends Command<UnionLeaderMessage.UnionAbdicateRequest> {

	@Override
	public void execute(MessageSource messageSource, UnionLeaderMessage.UnionAbdicateRequest request) {
		String playerCode = messageSource.getTag();
		String code = request.getCode();

		UnionLeaderMessage.UnionAbdicateResponse.Builder response = UnionLeaderMessage.UnionAbdicateResponse.newBuilder();

		// 盟主权限
		UnionPlayerEntry entry = new UnionPlayerEntry(playerCode);
		Result result = new UnionHandle().checkPlayerUnionLeader(entry);
		if (!result.equals(Result.UnionLeader)) {
			send(messageSource, response, result);
			return;
		}
		RedisLock uLock = UnionBean.lock(entry.getUnionBean().getCode());
		try {
			if (uLock.tryLock()) {
				UnionBean union = entry.reloadUnionBean();

				if (!union.getMemberList().contains(code) && !union.getViceList().contains(code)) {
					send(messageSource, response, Result.UnionTargetNotMember);// 此人不是成员
					return;
				}
				if (union.getMemberList().contains(code)) {
					union.getMemberList().remove(code);
				}
				if (union.getViceList().contains(code)) {
					union.getViceList().remove(code);
				}
				union.setLeader(code);
				union.getMemberList().add(playerCode);
				union.set();
				union.active();

				response.setCode(union.getLeader());

				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			uLock.unlock();
		}
	}

	private void send(MessageSource messageSource, UnionLeaderMessage.UnionAbdicateResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}